//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by 张远文 on 16/4/27.
//  Copyright © 2016年 张远文. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {

    //用户的信息
    var account: UserAccount?
    
    //是否已经登录
    var userLogin: Bool {
        
        return account?.access_token != nil
    }
    
    //获取token
    var token: String? {
        
        return account?.access_token
    }
    
    //获取用户名
    var userName: String? {
        
        return account?.name
    }
    
    //获取用户头像
    var headURL: NSURL? {
        
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    
    override init() {
        account = UserAccount.loadAccount()
    }
    
    func loadAccessToken(code: String,finished: (error : NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        
        NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parameters) { (result, error) in
            if error != nil {
                print(error)
                finished(error: error)
                return
            }
            print(result)
            let account = UserAccount(dict: result!)
            self.loadUserInfo(account, finished: finished)
        }
    }
    
    private func loadUserInfo(account: UserAccount,finished: (error : NSError?) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["access_token" : account.access_token!, "uid" : account.uid!]
        
        
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parameters) { (result, error) in
            if error != nil {
                print(error)
                finished(error: error)
                return
            }
            
            //请求用户资料
            account.avatar_large = result!["avatar_large"] as? String
            account.name = result!["name"] as? String
            account.saveAccount()
            finished(error: nil)
        }
    }
}
